
import Response from './response'

export default function(url, config) {

    return new Promise(function(resolve, reject){

        var xmlRequest = undefined;

        if (typeof XMLHttpRequest != 'undefined') {
            xmlRequest = new XMLHttpRequest();
        } else {
            xmlRequest = new ActiveXObject('Microsoft.XMLHTTP');
        }
        var method = (config.method || 'get').toLowerCase();
        var body = config.body || {};
        var contentType = config.contentType || 'application/x-www-form-urlencoded';

        xmlRequest.open(method, url);
        xmlRequest.timeout = config.timeout || 20 * 1000;

        for (var header in config.headers) {
            xmlRequest.setRequestHeader(header, config.headers[header]);
        }

        xmlRequest.send(body);

        var onreadystatechange = function() {

            if (xmlRequest.readyState == 3) {
                // progress();
                return;
            }
            if (xmlRequest.readyState != 4) {
                return;
            }
            //处理响应头信息
            var headers = {};
            var rheaders = xmlRequest.getAllResponseHeaders().split('\n');
            for(var n = 0; n<rheaders.length;n++){
                var item = rheaders[n];
                var h = item.match(/((?!:).)*(?:)/g)[0];
                if(!h){
                    continue;
                }
                headers[h] = xmlRequest.getResponseHeader(h);
            }
            var response = new Response(xmlRequest.responseXML || xmlRequest.responseText,{
                status: xmlRequest.status,
                statusText: xmlRequest.statusText,
                timeout: xmlRequest.timeout,
                headers: headers,
            })
            resolve(response)
        };
        //
        xmlRequest.ontimeout = function (e) {
            //     // XMLHttpRequest 超时。在此做某事。
            var response = new Response('',{
                status: 0,
                statusText: 'timeout',
                timeout: xmlRequest.timeout,
            })
            resolve(response)
        }
        xmlRequest.onreadystatechange = onreadystatechange
    })
}


